import React, { useRef } from "react";
import SwiperCore from "swiper";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css/navigation";
import { Navigation } from "swiper/modules";
import { Product } from "@/business.InterfaceLayer/type";
import CardBlockCeil from "../../UI_KIT/Cells/CardBlock.ceil";
import ImageAtom from "../../UI_KIT/Atoms/Image.Atom";
import ImageEnum from "../../UI_KIT/Atoms/Image.Atom/enum";
import ArrowRightIcon from "../../shared/icons/arrow-right.svg?react";
import ArrowLeftIcon from "../../shared/icons/arrow-left.svg?react";
import { HitsBlockProps } from "./type";

SwiperCore.use([Navigation]);

const HitsBlock: React.FC<HitsBlockProps> = (props) => {
  const { products } = props;

  const swiperRef = useRef<SwiperCore>();

  const renderCardBlocks = React.useMemo(() => {
    if (!products || products.length === 0) return null; // Проверка на наличие товаров

    return products.slice(0, 12).map(
      (
        product: Product // Ограничение до трех товаров
      ) => (
        <SwiperSlide key={product.product_id}>
          <CardBlockCeil
            id={product.product_id}
            price={product.price}
            title={product.title}
            brand={product.brand}
            color={product.colors}
            image={product.img_paths[0]}
          />
        </SwiperSlide>
      )
    );
  }, [products]);

  return (
    <div className="relative">
      <Swiper
        slidesPerView={4}
        spaceBetween={25}
        loop={true}
        onBeforeInit={(swiper) => {
          swiperRef.current = swiper;
        }}
        breakpoints={{
          320: { slidesPerView: 1 },
          375: { slidesPerView: 1 },
          425: { slidesPerView: 1 },
          768: { slidesPerView: 2, spaceBetween: 30 },
          1024: { slidesPerView: 3, spaceBetween: 20 },
          1200: { slidesPerView: 4, spaceBetween: 25 },
        }}
      >
        {renderCardBlocks}
      </Swiper>
      <div className="absolute bottom-1/2 left-[-10px] z-10 cursor-pointer fill-tiffany active:fill-bg_active hover:fill-bg_hover">
        <ImageAtom
          icon={<ArrowLeftIcon />}
          className="w-14 h-14"
          type={ImageEnum.enum_defaultSvg}
          onClick={() => swiperRef.current?.slidePrev()}
        />
      </div>
      <div className="absolute bottom-1/2 right-[-10px] z-10 cursor-pointer fill-tiffany active:fill-bg_active hover:fill-bg_hover">
        <ImageAtom
          type={ImageEnum.enum_defaultSvg}
          className="w-14 h-14"
          icon={<ArrowRightIcon />}
          onClick={() => swiperRef.current?.slideNext()}
        />
      </div>
    </div>
  );
};

export default React.memo(HitsBlock);
